const express = require("express");
const router = express.Router();
let multer = require("multer");
let path = require("path");
let os = require("os");
let fs = require("fs");
const Docxtemplater = require("docxtemplater");
const PizZip = require("pizzip");

let storage = multer.diskStorage({
  destination: function (req, file, cb) {
    let uploadPath = path.join(__dirname, "../public/uploadPath");
    let date = new Date();
    let datePath = path.join(
      uploadPath,
      `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
    );

    if (!fs.existsSync(datePath)) {
      fs.mkdirSync(datePath, { recursive: true });
    }

    cb(null, datePath);
  },
  filename: function (req, file, cb) {
    let nameParts = file.originalname.split(".");
    let extension = nameParts.pop();
    let fileNameWithoutExtension = nameParts.join(".");
    let timestamp = new Date().getTime();
    let newFileName = `${fileNameWithoutExtension}-${timestamp}.${extension}`;
    cb(null, newFileName);
  },
});

let upload = multer({ storage: storage });

router.post(
  "/api/v1/upload-file",
  upload.any(),
  async function (req, res, next) {
    try {
      let file;
      console.log("req.files: ", req.files);
      if (req.files && req.files.length > 0) {
        file = req.files[0];
      } else if (req.file) {
        file = req.file;
      }

      if (!file) {
        return res.status(400).jsonp({ error: "No file uploaded" });
      }

      let fileUrl = path.relative(
        path.join(__dirname, "../public/uploadPath"),
        path.join(file.destination, file.filename)
      );
      fileUrl = fileUrl.replace(/\\/g, "/");
      res.jsonp({ code: 20000, filename: file.originalname, url: fileUrl });
    } catch (err) {
      res.status(501).jsonp(err);
    }
  }
);

router.post("/api/v1/download-file", function (req, res) {
  // 从请求的URL中获取文件路径
  let downloadName = req.body.downloadName;
  let fileName = req.body.fileName;
  let uploadPath = path.join(__dirname, "../public/uploadPath");
  let filePath = path.join(uploadPath, downloadName);
  filePath = path.normalize(filePath).replace(/\\/g, "/");
  if (!fs.existsSync(filePath)) {
    return res.status(501).send("文件不存在");
  }
  res.download(filePath, fileName);
});

router.post("/api/v1/delete-file", function (req, res) {
  let fileName = req.body.fileName;
  let uploadPath = path.join(__dirname, "../public/uploadPath");
  let filePath = path.join(uploadPath, fileName);
  filePath = path.normalize(filePath).replace(/\\/g, "/");
  if (!fs.existsSync(filePath)) {
    return res.status(404).send("文件不存在");
  }
  fs.unlinkSync(filePath);
  res.send("文件已删除");
});

router.post("/api/v1/replace-word-fields", function (req, res) {
  let url = req.body.url;
  let fields = req.body.fields;
  if (!url) {
    return res.status(400).send("请求中缺少 url");
  }
  let uploadPath = path.join(__dirname, "../public/uploadPath");
  let filePath = path.join(uploadPath, url);
  filePath = path.normalize(filePath).replace(/\\/g, "/");
  console.log(filePath);
  if (!fs.existsSync(filePath)) {
    return res.status(404).send("文件不存在");
  }

  let content = fs.readFileSync(filePath, "binary");
  let zip = new PizZip(content);
  let doc = new Docxtemplater();
  doc.loadZip(zip);
  doc.setData(fields);
  try {
    doc.render();
  } catch (error) {
    return res.status(500).send("替换字段失败");
  }

  let buf = doc.getZip().generate({ type: "nodebuffer" });
  fs.writeFileSync(filePath, buf);
  res.send("字段已替换");
});

router.post("/api/v1/copy-word-fields", function (req, res) {
  let url = req.body.url;
  let fields = req.body.fields;

  // 检查请求体中是否包含必要的参数
  if (!url) {
    return res.status(400).send("请求中缺少 url");
  }

  // 拼接文件路径
  let uploadPath = path.join(__dirname, "../public/uploadPath");
  let filePath = path.join(uploadPath, url);
  filePath = path.normalize(filePath).replace(/\\/g, "/");

  // 检查文件是否存在
  if (!fs.existsSync(filePath)) {
    return res.status(404).send("文件不存在");
  }

  // 创建新的文件路径
  let date = new Date();
  let datePath = path.join(
    uploadPath,
    `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
  );
  if (!fs.existsSync(datePath)) {
    fs.mkdirSync(datePath, { recursive: true });
  }
  let newFilePath = path.join(datePath, "new_" + path.basename(url));
  newFilePath = path.normalize(newFilePath).replace(/\\/g, "/");

  // 复制文件
  fs.copyFileSync(filePath, newFilePath);

  // 读取文件内容并进行处理
  let content = fs.readFileSync(newFilePath, "binary");
  let zip = new PizZip(content);
  let doc = new Docxtemplater();
  doc.loadZip(zip);
  doc.setData(fields);

  // 渲染文档
  try {
    doc.render();
  } catch (error) {
    // 渲染失败，记录错误信息，但不中断流程，继续处理下一个请求
    console.log("渲染文档失败:", error);
    // 返回原始文件的 URL 和名称信息
    return res.send({ url: url, name: path.basename(url) });
  }

  // 生成替换后的文档内容并写入文件
  let buf = doc.getZip().generate({ type: "nodebuffer" });
  fs.writeFileSync(newFilePath, buf);

  // 返回成功响应
  res.send({
    url: path.relative(uploadPath, newFilePath).replace(/\\/g, "/"),
    name: path.basename(url),
  });
});
module.exports = router;
